import axios from 'axios'

let error = console.error

const api = '/categories/'

export default function getTree (cb, fcb = () => error('getTree')) {
  axios.get(api).then(res => {
    let data = res.data
    cb(foreach(data))
  }).catch(error => {
    fcb(error)
  })
}

function replaceName (node) {
  let d = {
    value: node.id,
    label: node.name
  }
  delete node.name
  delete node.parentId
  delete node.sort
  Object.assign(node, d)
  if (node.children) {
    foreach(node.children)
  }
}

function foreach (nodes) {
  for (let n of nodes) {
    replaceName(n)
  }
  return nodes
}
